package com.tony.demo.widgets;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import android.util.AttributeSet;
import android.view.View;

import com.puhui.lib.utils.DMLog;
import com.puhui.lib.utils.DensityUtil;
import com.tony.demo.R;

import java.util.Calendar;


public class ClockViewCopy extends View {
//    private Paint clockCirclePaint;  //时钟圆形画笔
//    private Paint secondUnitPaint;  //秒单元画笔
//    private Paint minutesUnitPaint;  //分单元画笔
//    private Paint hourPaint;  //小时指针画笔
//    private Paint hourNumPaint;  //小时数字画笔
//    private Paint minutePaint;  //分钟指针画笔
//    private Paint secondPaint;  //秒针画笔

    private Paint clockPaint;
    private int mViewSize;
    private Calendar calendar;  //根据calendar获取时分秒值
    private int laseSecond = 0;  //用来测试使用，查看是否跳动了一秒

    public ClockViewCopy(Context context) {
        this(context, null);
    }

    public ClockViewCopy(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ClockViewCopy(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        clockPaint = new Paint();
        int clockColor = ContextCompat.getColor(context, R.color.color_333333);
        clockPaint.setColor(clockColor);
        clockPaint.setStrokeWidth(4);
        clockPaint.setStyle(Paint.Style.STROKE);
        clockPaint.setAntiAlias(true);  //去除锯齿
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        mViewSize = width > height ? height : width;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mViewSize > 0) {
            clockPaint.setColor(Color.BLACK);  //因为在最后将颜色值设置成了白色，所以这里需要回复一下

            //画时钟的圆
            float center = mViewSize / 2f;
            float radius = mViewSize / 2f - 2;  //这里不减去2的话，会导致圆的上下左右被切去一点点
            canvas.translate(center, center);
            canvas.drawCircle(0, 0, radius, clockPaint);

            canvas.save();
            float minuteLength = radius / 10;
            float hourLength = minuteLength + 10;
            for (int i = 0; i < 60; i++) {
                if (i % 5 == 0) {
                    //小时刻度
                    clockPaint.setStrokeWidth(4);
                    canvas.drawLine(0, -radius, 0, -radius + hourLength, clockPaint);
                } else {
                    //分钟刻度
                    clockPaint.setStrokeWidth(2);
                    canvas.drawLine(0, -radius, 0, -radius + minuteLength, clockPaint);
                }

                canvas.rotate(6);
            }
            canvas.restore();

            //画分钟刻度下的更小的刻度
            canvas.save();
//            for (int i = 0; i < 300; i++) {
//                canvas.rotate(1.2f);
//                clockPaint.setStrokeWidth(2);
//                canvas.drawLine(0, -radius, 0, -radius + minuteLength - 10, clockPaint);
//            }
            //用下面这个可以避免过度绘制
            for (int i = 0; i < 240; i++) {
                canvas.rotate((i > 0 && i % 4 == 0) ? 2.4f : 1.2f);
                clockPaint.setStrokeWidth(2);
                canvas.drawLine(0, -radius, 0, -radius + minuteLength - 10, clockPaint);
            }
            canvas.restore();

            for (int i = 0; i < 12; i++) {
                //画小时数值
                clockPaint.setStrokeWidth(2);
                clockPaint.setTextSize(DensityUtil.dip2px(getContext(), 10));
                clockPaint.setStyle(Paint.Style.FILL);

                float translateTemp = -radius + hourLength + getTextHeight(clockPaint) / 2;
                canvas.rotate(i * 30);
                canvas.translate(0, translateTemp);
                canvas.rotate(-i * 30);

                String text = i == 0 ? String.valueOf(12) : String.valueOf(i);
                canvas.drawText(text, -getTextWidth(clockPaint, text) / 2, getTextHeight(clockPaint) / 3, clockPaint);
//                canvas.rotate(30);

                canvas.rotate(i * 30);
                canvas.translate(0, -translateTemp);
                canvas.rotate(-i * 30);
            }

            float hourTextY = -radius + radius / 10 + getTextHeight(clockPaint);
            //画当前时间指针
            calendar = Calendar.getInstance();
            int hour = calendar.get(Calendar.HOUR);
            int minute = calendar.get(Calendar.MINUTE);
            int second = calendar.get(Calendar.SECOND);

            if (second - laseSecond == 2) {
                DMLog.e(this.getClass().getCanonicalName(), "秒针跳动了2秒");
            }
            laseSecond = second;

            canvas.save();  //时针
            canvas.rotate(hour * 30);
            clockPaint.setStyle(Paint.Style.FILL);
            clockPaint.setStrokeWidth(10);
            canvas.drawLine(0, 30, 0, hourTextY + dipToPx(20), clockPaint);
            canvas.restore();

            canvas.save();  //分针
            canvas.rotate(minute * 6);
            clockPaint.setStyle(Paint.Style.FILL);
            clockPaint.setStrokeWidth(7);
            canvas.drawLine(0, 30, 0, hourTextY + dipToPx(10), clockPaint);
            canvas.restore();

            canvas.save();  //秒针
            canvas.rotate(second * 6);
            clockPaint.setStyle(Paint.Style.FILL);
            clockPaint.setStrokeWidth(3);
            canvas.drawLine(0, 30, 0, hourTextY - dipToPx(5), clockPaint);
            canvas.restore();

            //画中心圆点
            clockPaint.setColor(Color.WHITE);
            clockPaint.setStyle(Paint.Style.STROKE);
            canvas.drawCircle(0, 0, 2, clockPaint);
            postInvalidateDelayed(1000 - calendar.get(Calendar.MILLISECOND));
//            postInvalidateDelayed(1000);
            //time = 1005~1020之间，差不多每隔50-52秒就出现一次跳动的情况
//            DMLog.e(this.getClass().getCanonicalName(), "time = " + (System.currentTimeMillis() - lastTime));
//            lastTime = System.currentTimeMillis();
        }
    }

    /**
     * 错误的(应该说不是高效的)绘制方法
     */
    private void errorDraw() {
        //画时分秒刻度
//        float startX = 0;
//        float startY = 0;
//        float endX;
//        float endY;
//        double angle = 6 * Math.PI / 180;
//        startX = radius * (float) Math.sin(angle);
//        startY = radius * (float) Math.cos(angle);
//
//        endX = startX - deltaLength * (float) Math.sin(angle);
//        endY = startY - deltaLength * (float) Math.cos(angle);
//        canvas.drawLine(startX, startY, endX, endY, clockPaint);
//
//        if (i % 5 == 0) {
//            //画小时数值
//            float textX = startX - 60 * (float) Math.sin(angle);
//            float textY = startY - 60 * (float) Math.cos(angle);
//            int hourNum = i / 5 == 0 ? 12 : i / 5;
//            clockPaint.setStrokeWidth(2);
//            clockPaint.setTextSize(20);
//            canvas.drawText(hourNum + "", textX, textY, clockPaint);
//        }
    }

    private Rect rect;

    private int getTextWidth(Paint paint, String text) {
        if (null == rect) {
            rect = new Rect();
        }
        paint.getTextBounds(text, 0, text.length(), rect);
        return rect.width();   //rect.height();
    }

    private int textHeight = 0;

    private float getTextHeight(Paint paint) {
        if (textHeight == 0) {
            Paint.FontMetricsInt fontMetricsInt = paint.getFontMetricsInt();
            textHeight = fontMetricsInt.descent - fontMetricsInt.ascent;
            return textHeight;
        }
        return textHeight;
    }
//    private float getTextHeight(Paint paint) {
//        Paint.FontMetricsInt fontMetricsInt = paint.getFontMetricsInt();
//        return fontMetricsInt.descent - fontMetricsInt.ascent;
//    }

    /**
     * @param fontSize 字体大小
     * @return 字体大小对应的文字内容所占空间的高度  参看Paint_Text.png图
     */
    public int getFontHeight(float fontSize) {
        Paint paint = new Paint();
        paint.setTextSize(fontSize);
        Paint.FontMetrics fm = paint.getFontMetrics();
        return (int) Math.ceil(fm.descent - fm.ascent);
    }

    private int dipToPx(int dip) {
        return DensityUtil.dip2px(getContext(), dip);
    }
}
